package org.jpro.modules.system.service.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.jpro.common.jpa.Specifications;
import org.jpro.common.util.DateUtils;
import org.jpro.common.util.security.Digests;
import org.jpro.common.util.security.Encodes;
import org.jpro.modules.system.dao.UserRepository;
import org.jpro.modules.system.entity.User;
import org.jpro.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <P>功能描述 : 用户service实现 </P>
 * <P>File name : UserServiceImpl </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/4 上午12:05</P>
 */
@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Page<User> search(String name, String phone, Date gtCreateDate, Date ltCreateDate, PageRequest pageRequest) {

        Specification<User> userSpecification = Specifications.<User> and()// and条件
                .like(StringUtils.isNotEmpty(name), "name", "%" + name + "%")// 用户名like
                .like(StringUtils.isNoneBlank(phone), "phone", "%" + phone + "%")// 手机号like
                .ge(gtCreateDate != null, "createDate", gtCreateDate)// 创建时间大于
                .le(ltCreateDate != null, "createDate", ltCreateDate).build();// 创建时间小于
        return userRepository.findAll(userSpecification, pageRequest);
    }

    @Override
    @Transactional
    public void save(User user) {
        entryptPassword(user);
        user.setCreateDate(DateUtils.getSysTimestamp());
        userRepository.save(user);
    }

    @Override
    @Transactional
    public void update(User user) {
        userRepository.save(user);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        // TODO: 2017/3/15 超级管理员不能自己删除自己，疯啦
        userRepository.delete(id);
    }

    @Override
    public boolean checkPassword(User user, String oldPassword) {
        byte[] salt = Encodes.decodeHex(user.getSalt());
        byte[] hashPassword = Digests.sha1(oldPassword.getBytes(), salt, HASH_INTERATIONS);
        if (user.getPassword().equals(Encodes.encodeHex(hashPassword))) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional
    public void updatePwd(User user) {
        entryptPassword(user);
        userRepository.save(user);
    }

    /**
     * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
     */
    private void entryptPassword(User user) {

        byte[] salt = Digests.generateSalt(SALT_SIZE);
        user.setSalt(Encodes.encodeHex(salt));

        byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
        user.setPassword(Encodes.encodeHex(hashPassword));

    }

    @Override
    public User getUser(String loginName) {
        return userRepository.findByLoginName(loginName);
    }

    @Override
    public User get(Integer id) {
        return userRepository.getOne(id);
    }

    @Override
    @Transactional
    public void updateUserLogin(User user) {
        user.setLoginCount((user.getLoginCount() == null ? 0 : user.getLoginCount()) + 1);
        user.setPreviousVisit(user.getLastVisit());
        user.setLastVisit(DateUtils.getSysTimestamp());
        update(user);
    }

}
